package controller

import (
	"fmt"
	"gin-vue/common"
	"gin-vue/dto"
	"gin-vue/model"
	"gin-vue/response"
	"gin-vue/utils"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"net/http"
)

func Register(context *gin.Context) {
	DB := common.GetDB()
	name := context.PostForm("name")
	phone := context.PostForm("phone")
	password := context.PostForm("password")

	if len(name) == 0 {
		name = utils.RandomString(10)
	}

	if len(phone) != 11 {
		context.JSON(http.StatusBadRequest, gin.H{"code": 422, "msg": "手机号必须11位"})
		return
	}

	if len(password) < 6 {
		context.JSON(http.StatusBadRequest, gin.H{"code": 422, "msg": "密码不得小于6位"})
		return
	}

	hasedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		context.JSON(http.StatusInternalServerError, gin.H{"code": "500", "msg": "加密错误"})
		return
	}
	newUser := model.User{

		Name:     name,
		Phone:    phone,
		Password: string(hasedPassword),
	}
	DB.Create(&newUser)

	context.JSON(200, gin.H{"msg": "注册成功"})
}

func Login(context *gin.Context) {
	DB := common.GetDB()
	//获取参数
	phone := context.PostForm("phone")
	password := context.PostForm("password")
	//登录验证

	if len(phone) != 11 {
		response.Response(context, http.StatusUnprocessableEntity, 422, nil, "手机号码必须11位")
		context.JSON(http.StatusBadRequest, gin.H{"code": 422, "msg": "手机号必须11位"})
		return
	}

	if len(password) < 6 {
		context.JSON(http.StatusBadRequest, gin.H{"code": 422, "msg": "密码不得小于6位"})
		return
	}

	//判断手机号是否存在
	var user model.User
	DB.Where("phone=?", phone).First(&user)
	if user.ID == 0 {
		fmt.Println("DB find error")
		context.JSON(http.StatusBadRequest, gin.H{
			"msg": "查询条件未找到",
		})
		return
	}

	//判断密码是否正确,验证前端发过来的数据与数据库中的数据
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"msg": "密码校验失败",
		})
	}
	//发送token
	token, err := common.ReleaseToken(user)
	if err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"msg": "jwt失败",
		})
		return
	}
	//返回结果
	context.JSON(200, gin.H{
		"msg":  "登录成功",
		"data": gin.H{"token": token},
	})
}

func Info(context *gin.Context) {
	user, _ := context.Get("user")
	context.JSON(http.StatusOK, gin.H{
		"code": 200,
		"data": dto.ToUserDto(user.(model.User)),
	})
}
